const express = require('express')
const utils = require('utility')

const Router = express.Router();
const model = require('./model')
const User = model.getModel('user')
const _filter = { pwd: 0, __v: 0 }
Router.get('/info', function (req, res) {
  const { userid } = req.cookies
  if (!userid) {
    return res.json({
      code: 1
    })
  }
  User.findOne({ _id: userid }, _filter, function (e, d) {
    if (d) {
      return res.json({ code: 0, data: d })
    }
    if (e) {
      return res.json({ code: 1, msg: '后端出错了' })
    }
    if (!d) {
      return res.json({ code: 1 })
    }
  })
})

Router.get('/remove', function (req, res) {
  User.remove({}, function (e, d) {
    res.json({ msg: `数据清空` })
  })
})

Router.get('/list', function (req, res) {
  const type = req.query.type && req.query.type ==='boss'?'genius':'boss'
  User.find({type}, function (e, d) {
    return res.json({code:0,data:d})
  })
})

Router.post('/register', function (req, res) {
  const { user, type, pwd } = req.body
  User.findOne({ user }, function (e, d) {
    if (d) {
      return res.json({ code: 1, msg: '用户名不能重复' })
    }
    const userModel = new User({ user, type, pwd: md5Pwd(pwd) })
    userModel.save(function (e, d) {
      const { user, type, _id } = d
      res.cookie('userid', _id)
      return res.json({ code: 0, data: { user, type, _id } })
    })
  })
})
Router.post('/login', function (req, res) {
  const { user, pwd } = req.body
  User.findOne({ user, pwd: md5Pwd(pwd) }, _filter, function (e, d) {
    if (!d) {
      return res.json({ code: 1, msg: '用户名或密码错误' })
    }
    res.cookie('userid', d._id)
    return res.json({ code: 0, data: d })
  })
})
Router.post('/update', function (req, res) {
  const body = req.body
  const { userid } = req.cookies
  if (userid){
    User.findByIdAndUpdate(userid, body, function (err, doc) {
      const data = Object.assign({}, {
        type: doc.type,
        user: doc.user
      }, body)
      return res.json({ data: data, code: 0 })
    })
  }
})

function md5Pwd(pwd) {
  const salt = 'qdx?love:no@good_©'
  return utils.md5(utils.md5(pwd + salt))
}

module.exports = Router
